我們今天要延續昨天的Final Mission — 5 日實作計畫,設計一個Galactic Explorer!
今日目標:製作「觀察日誌」功能,記錄每日探索心得。
我們要讓「宇宙觀察日誌」能夠永久保存,即使刷新頁面、關掉再開也不會消失~!
我們會用到三個關鍵概念:
Diary.vue在 src/views/ 裡新增一個檔案:
<template>
<main class="diary">
<h1>🌌 宇宙觀察日誌</h1>
<!-- 新增日誌輸入區 -->
<el-input
v-model="draft"
type="textarea"
rows="4"
placeholder="記錄今天的星際探索心得..."
/>
<el-button type="primary" @click="saveLog">💾 儲存</el-button>
<hr />
<!-- 日誌列表 -->
<ul class="logs">
<li v-for="log in logs" :key="log.id">
<p class="text">{{ log.text }}</p>
<small class="time">{{ log.time }}</small>
</li>
</ul>
</main>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
const draft = ref('')
const logs = ref([])
// ✅ 第一次載入頁面時,從 localStorage 取資料
onMounted(() => {
const saved = localStorage.getItem('diaryLogs')
if (saved) {
try {
logs.value = JSON.parse(saved)
} catch (err) {
console.error('localStorage 格式錯誤:', err)
logs.value = []
}
}
})
// ✅ 當 logs 改變時,更新 localStorage
watch(
logs,
(newVal) => {
localStorage.setItem('diaryLogs', JSON.stringify(newVal))
},
{ deep: true } // 深層監聽,確保每次內容變化都會保存
)
// ✅ 儲存新日誌
function saveLog() {
if (!draft.value) return
logs.value.unshift({
id: Date.now(),
text: draft.value,
time: new Date().toLocaleString()
})
draft.value = ''
}
</script>
<style scoped>
.diary {
max-width: 700px;
margin: auto;
padding: 20px;
font-family: 'Orbitron', system-ui;
color: #e0e7ff;
}
.logs {
list-style: none;
padding: 0;
}
.logs li {
background: rgba(167, 139, 250, 0.1);
border: 1px solid rgba(167, 139, 250, 0.3);
border-radius: 12px;
padding: 12px;
margin-top: 12px;
}
.text {
margin: 0 0 4px;
font-size: 1.1em;
}
.time {
font-size: 0.85em;
color: #a78bfa;
}
</style>
/diary 路由開啟 src/router/index.js,在 routes 陣列中加入:
import Diary from '../views/Diary.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/planets', name: 'planets', component: Planets },
{ path: '/diary', name: 'diary', component: Diary }, // ✨ 新增這行
{ path: '/:pathMatch(.*)*', name: '404', component: NotFound }
]
})
在 App.vue(或 Navbar 元件)加上:
<router-link to="/diary">🪐 宇宙觀察日誌</router-link>

如此重新整理頁面後資料仍會存在!
參考資源
https://vuejs.org/guide
https://www.runoob.com/vue3